import tkinter as tk
from tkinter import ttk, messagebox, Canvas, Frame, simpledialog
from PIL import Image, ImageTk, ImageGrab
import base64
import requests
import io
import threading
import os

# 默认配置
DEFAULT_SETTINGS = {
    "api_key": "sk-3c1bd5cfaabb49c88750ba99b1ebf1e1",
    "base_url": "https://maas.hikvision.com.cn/v1/chat/completions",
    "version_model": "Qwen2.5-VL-72B-Instruct-1874024994729345025-test0319",
    "llm_base_url": "http://lanz.hikvision.com/v3/openai/deepseek-v3",
    "llm_model": "DeepSeek-V3-0324",
    "screenshot_border_size": 3,
    "screenshot_border_color": "#FF5722"
}

OCR_PROMPT = """
分析图片，思考解题步骤，如果是平面几何、函数、立体几何相关题目，
请按照题目内容生成相应得 Geogebra 绘图指令，并补充其他解题必要的辅助线。
除了生成题目内容的Geogebra 绘图指令外，如果是选择题请给每个选项生成需要的 
Geogebra 指令，如果是解答题并且分小题的，按照小题生成 Geogebra 指令。
必须反思Geogebra是否存在每个指令，并且使用是否正确。
"""

GEN_HTML_PROMPT = """
#角色
你是一位 GeoGebra 画图专家
•   精通GeoGebra的2D/3D图形绘制
•   熟悉GeoGebra JavaScript API（ggbApp操作）
•   能够通过HTML/CSS/JS实现交互式绘图界面

功能需求
1. HTML页面结构
•   头部：
•   左侧：GeoGebra绘图区域（固定尺寸，非100%）
•   右侧：控制面板（包含按钮和输入框）
2. GeoGebra初始化
•   使用官方CDN引入deployggb.js
•   初始化参数参考：
var parameters = { "id": "ggbApplet", "appName": "classic", "width": "600", "height": "500", "showMenuBar": true, "showAlgebraInput": true, "showToolBar": true, "showToolBarHelp": true, "showResetIcon": true, "enableLabelDrags": true, "enableShiftDragZoom": true, "enableRightClick": true, "errorDialogsActive": false, "useBrowserForJS": false, "allowStyleBar": false, "preventFocus": false, "showZoomButtons": true, "capturingThreshold": 3, "showFullscreenButton": true, "scale": 1, "disableAutoScale": false, "allowUpscale": false, "clickToLoad": false, "buttonRounding": 0.7, "buttonShadows": false, "language": "zh-CN", "appletOnLoad": function(api) { window.ggbApp = api;  } }; 

限制条件：
3. 重置图表使用window.ggbApp.reset()
4. 初始化参数中不要使用materialid， filename，base64
5. 不要设置全局变量ggbApp，只在appletOnLoad 中设置 window.ggbApp = api，后续都使用ggbApp操作Geogebra 的 API
6. GeoGebra 命令执行使用ggbApp.evalCommand('')方法，单个命令执行，命令不使用中文名称，记住要思考每个命令是否存在，使用方式是否正确。
7. 兼容性
•   支持现代浏览器（Chrome/Firefox/Edge）
•   绘图区域尺寸必须为固定值（如800x600），parameters参数中的width和height不要修改，绝对不能改成100%。
Geogebra大小自适应窗口大小，参考如下代码调整GeoGebra应用大小 function resizeApplet() { const container = document.querySelector('.ggb-container'); const width = container.offsetWidth; const height = container.offsetHeight; // 如果应用已加载，强制重绘 if (ggbApp && typeof ggbApp.recalculateEnvironments === 'function') { ggbApp.setSize(width, height); } }
•   页面样式和字体使用font-awesome和google-fonts

输出要求
•   提供完整的HTML文件，包含内联CSS和JS
•   代码注释关键步骤（如GeoGebra初始化、图形生成逻辑）

请按照上面生成的 Geogebra指令生成html演示课件。如果是选择题请给每个选项生成一个操作按钮，点击按钮显示GeoGebra绘图内容，并在切换选项时可以全部删除之前选项生成的内容。如果是解答题并且分小题的，请给每个小题生成一个操作按钮，点击按钮显示GeoGebra绘图内容，并在切换小题时可以全部删除之前选项生成的内容。点击不同按钮显示相应的解题思路。

请按照上面生成的 Geogebra指令生成html演示课件。
要求：
1、如果是选择题请给每个选项生成一个操作按钮，点击按钮显示GeoGebra绘图内容，并在切换选项时可以全部删除之前选项生成的内容。
2、如果是解答题并且分小题的，请给每个小题生成一个操作按钮，点击按钮显示GeoGebra绘图内容，并在切换小题时可以全部删除之前选项生成的内容。
3、点击不同按钮显示相应的解题思路。
4、如果Geogebra指令有错误，请直接修改。
"""

class SettingsDialog(simpledialog.Dialog):
    """API密钥和基础URL配置对话框"""
    def __init__(self, parent, settings):
        self.settings = settings
        super().__init__(parent, title="API设置")
    
    def body(self, frame):
        # API密钥输入
        ttk.Label(frame, text="OpenAI API密钥:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.api_key_var = tk.StringVar(value=self.settings["api_key"])
        self.api_key_entry = ttk.Entry(frame, textvariable=self.api_key_var, width=40)
        self.api_key_entry.grid(row=0, column=1, padx=5, pady=5)
        
        # 基础URL输入
        ttk.Label(frame, text="OpenAI基础URL:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.base_url_var = tk.StringVar(value=self.settings["base_url"])
        self.base_url_entry = ttk.Entry(frame, textvariable=self.base_url_var, width=40)
        self.base_url_entry.grid(row=1, column=1, padx=5, pady=5)
        
        # 模型选择
        ttk.Label(frame, text="模型:").grid(row=2, column=0, padx=5, pady=5, sticky="w")
        self.model_var = tk.StringVar(value=self.settings["model"])
        self.model_entry = ttk.Entry(frame, textvariable=self.model_var, width=40)
        self.model_entry.grid(row=2, column=1, padx=5, pady=5)
        
        # 截图边框设置
        ttk.Label(frame, text="截图边框大小:").grid(row=3, column=0, padx=5, pady=5, sticky="w")
        self.border_size_var = tk.IntVar(value=self.settings["screenshot_border_size"])
        self.border_size_spin = ttk.Spinbox(frame, from_=1, to=10, width=5, textvariable=self.border_size_var)
        self.border_size_spin.grid(row=3, column=1, padx=5, pady=5, sticky="w")
        
        ttk.Label(frame, text="边框颜色:").grid(row=4, column=0, padx=5, pady=5, sticky="w")
        self.border_color_var = tk.StringVar(value=self.settings["screenshot_border_color"])
        self.border_color_entry = ttk.Entry(frame, textvariable=self.border_color_var, width=10)
        self.border_color_entry.grid(row=4, column=1, padx=5, pady=5, sticky="w")
        
        return self.api_key_entry
    
    def apply(self):
        self.settings["api_key"] = self.api_key_var.get()
        self.settings["base_url"] = self.base_url_var.get()
        self.settings["model"] = self.model_var.get()
        self.settings["screenshot_border_size"] = self.border_size_var.get()
        self.settings["screenshot_border_color"] = self.border_color_var.get()

class ScreenshotTool:
    def __init__(self, root, callback, settings):
        self.root = root
        self.callback = callback
        self.settings = settings
        self.setup_ui()
        
        # 存储截图状态
        self.start_x = None
        self.start_y = None
        self.end_x = None
        self.end_y = None
        self.rect_id = None
        self.resize_handles = {}
        self.resizing = False
        self.moving = False
        self.adjust_mode = False
        
        # 绑定全局按键事件
        self.root.bind("<Escape>", self.cancel_screenshot)
        self.root.bind("<Return>", self.confirm_screenshot)

    def setup_ui(self):
        """创建截图界面元素"""
        self.canvas = Canvas(self.root, cursor="cross")
        self.canvas.pack(fill="both", expand=True)
        
        # 添加半透明遮罩
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        self.overlay = self.canvas.create_rectangle(
            0, 0, screen_width, screen_height, 
            fill="#000000", stipple="gray12"
        )
        
        info_text = "拖拽选择截图区域 (ESC 取消)"
        self.info_label = self.canvas.create_text(
            screen_width // 2, 20, 
            text=info_text, 
            fill="white", 
            font=("Arial", 14, "bold"),
            anchor="center"
        )
        
        # 绑定鼠标事件
        self.canvas.bind("<ButtonPress-1>", self.on_mouse_press)
        self.canvas.bind("<B1-Motion>", self.on_mouse_drag)
        self.canvas.bind("<ButtonRelease-1>", self.on_mouse_release)
    
    def cancel_screenshot(self, event=None):
        """取消截图操作"""
        self.root.unbind("<Escape>")
        self.root.unbind("<Return>")
        self.canvas.destroy()
        self.callback(None)
    
    def confirm_screenshot(self, event=None):
        """确认截图操作"""
        if self.adjust_mode and self.rect_id:
            self.capture_area()
    
    def create_resize_handles(self):
        """创建调整大小手柄和确认按钮"""
        # 删除现有手柄
        for handle in self.resize_handles.values():
            self.canvas.delete(handle)
        self.resize_handles = {}
        
        if not self.rect_id:
            return
            
        # 获取当前矩形坐标
        x1, y1, x2, y2 = self.canvas.coords(self.rect_id)
        
        # 创建四个角的手柄
        handle_size = 10  # 增大手柄尺寸，使其更容易点击
        handle_color = "#FF5722"
        
        # 左上角手柄
        self.resize_handles["nw"] = self.canvas.create_rectangle(
            x1 - handle_size, y1 - handle_size,
            x1 + handle_size, y1 + handle_size,
            fill=handle_color, outline=handle_color
        )
        
        # 右上角手柄
        self.resize_handles["ne"] = self.canvas.create_rectangle(
            x2 - handle_size, y1 - handle_size,
            x2 + handle_size, y1 + handle_size,
            fill=handle_color, outline=handle_color
        )
        
        # 左下角手柄
        self.resize_handles["sw"] = self.canvas.create_rectangle(
            x1 - handle_size, y2 - handle_size,
            x1 + handle_size, y2 + handle_size,
            fill=handle_color, outline=handle_color
        )
        
        # 右下角手柄
        self.resize_handles["se"] = self.canvas.create_rectangle(
            x2 - handle_size, y2 - handle_size,
            x2 + handle_size, y2 + handle_size,
            fill=handle_color, outline=handle_color
        )
        
        # 创建确认按钮（右下角）
        confirm_btn_x = x2 - 50
        confirm_btn_y = y2 + 40
        
        self.confirm_btn = self.canvas.create_rectangle(
            confirm_btn_x - 25, confirm_btn_y - 25,
            confirm_btn_x + 25, confirm_btn_y + 25,
            fill="#4CAF50", outline="#4CAF50", width=2
        )
        self.confirm_text = self.canvas.create_text(
            confirm_btn_x, confirm_btn_y,
            text="✓", 
            fill="white", 
            font=("Arial", 20, "bold"),
            anchor="center"
        )
        
        # 创建取消按钮（在确认按钮右侧）
        cancel_btn_x = x2 + 50
        cancel_btn_y = y2 + 40
        
        self.cancel_btn = self.canvas.create_rectangle(
            cancel_btn_x - 25, cancel_btn_y - 25,
            cancel_btn_x + 25, cancel_btn_y + 25,
            fill="#FF5252", outline="#FF5252", width=2
        )
        
        self.cancel_text = self.canvas.create_text(
            cancel_btn_x, cancel_btn_y,
            text="✕", 
            fill="white", 
            font=("Arial", 20, "bold"),
            anchor="center"
        )
        
        # 绑定确认按钮点击事件
        self.canvas.tag_bind(self.confirm_btn, "<Button-1>", self.confirm_screenshot)
        self.canvas.tag_bind(self.confirm_text, "<Button-1>", self.confirm_screenshot)
        
        # 绑定取消按钮点击事件
        self.canvas.tag_bind(self.cancel_btn, "<Button-1>", self.cancel_screenshot)
        self.canvas.tag_bind(self.cancel_text, "<Button-1>", self.cancel_screenshot)
        
        # 更新信息文本
        self.canvas.itemconfig(self.info_label, text="调整截图区域 (ESC 取消 / 按回车或点击按钮完成)")

    def on_mouse_press(self, event):
        """鼠标按下事件"""
        if self.adjust_mode:
            # 检查是否在调整手柄上
            for handle_id in self.resize_handles.values():
                if self.canvas.find_withtag("current") == (handle_id,):
                    self.resizing = True
                    self.resizing_handle = handle_id
                    return
            
            # 检查是否在矩形内部
            if self.canvas.find_withtag("current") == (self.rect_id,):
                self.moving = True
                self.move_start_x = event.x
                self.move_start_y = event.y
                return
        else:
            # 初始选择模式
            self.start_x = event.x
            self.start_y = event.y
            
            # 如果已有矩形，先删除
            if self.rect_id:
                self.canvas.delete(self.rect_id)
                for handle in self.resize_handles.values():
                    self.canvas.delete(handle)
                if hasattr(self, 'confirm_btn'):
                    self.canvas.delete(self.confirm_btn)
                    self.canvas.delete(self.confirm_text)
                    self.canvas.delete(self.cancel_btn)
                    self.canvas.delete(self.cancel_text)
            
            # 创建新矩形
            self.rect_id = self.canvas.create_rectangle(
                self.start_x, self.start_y, 
                self.start_x, self.start_y,
                outline=self.settings["screenshot_border_color"], 
                width=self.settings["screenshot_border_size"],
                dash=(4, 4)
            )

    def on_mouse_drag(self, event):
        """鼠标拖动事件"""
        if self.adjust_mode:
            if self.resizing:
                # 调整大小
                x1, y1, x2, y2 = self.canvas.coords(self.rect_id)
                
                if self.resizing_handle == self.resize_handles["nw"]:
                    x1 = event.x
                    y1 = event.y
                elif self.resizing_handle == self.resize_handles["ne"]:
                    x2 = event.x
                    y1 = event.y
                elif self.resizing_handle == self.resize_handles["sw"]:
                    x1 = event.x
                    y2 = event.y
                elif self.resizing_handle == self.resize_handles["se"]:
                    x2 = event.x
                    y2 = event.y
                    
                # 更新矩形位置
                self.canvas.coords(self.rect_id, x1, y1, x2, y2)
                
                # 更新手柄位置
                self.create_resize_handles()
                
            elif self.moving:
                # 移动整个矩形
                dx = event.x - self.move_start_x
                dy = event.y - self.move_start_y
                self.move_start_x = event.x
                self.move_start_y = event.y
                
                # 移动矩形
                self.canvas.move(self.rect_id, dx, dy)
                
                # 移动所有手柄
                for handle in self.resize_handles.values():
                    self.canvas.move(handle, dx, dy)
                
                # 移动确认按钮和取消按钮
                self.canvas.move(self.confirm_btn, dx, dy)
                self.canvas.move(self.confirm_text, dx, dy)
                self.canvas.move(self.cancel_btn, dx, dy)
                self.canvas.move(self.cancel_text, dx, dy)
        else:
            # 初始选择模式
            if self.rect_id and self.start_x is not None and self.start_y is not None:
                # 更新矩形位置
                self.canvas.coords(
                    self.rect_id, 
                    self.start_x, self.start_y, 
                    event.x, event.y
                )

    def on_mouse_release(self, event):
        """鼠标释放事件"""
        if self.adjust_mode:
            self.resizing = False
            self.moving = False
        else:
            if self.rect_id and self.start_x is not None and self.start_y is not None:
                # 获取选择的区域
                self.end_x, self.end_y = event.x, event.y
                x1 = min(self.start_x, self.end_x)
                y1 = min(self.start_y, self.end_y)
                x2 = max(self.start_x, self.end_x)
                y2 = max(self.start_y, self.end_y)
                
                # 确保选择区域足够大
                if (x2 - x1) > 10 and (y2 - y1) > 10:
                    # 更新矩形
                    self.canvas.coords(self.rect_id, x1, y1, x2, y2)
                    
                    # 进入调整模式
                    self.adjust_mode = True
                    self.create_resize_handles()
                else:
                    messagebox.showinfo("提示", "选择的区域太小，请重新选择")

    def capture_area(self):
        """捕获指定区域的屏幕截图"""
        # 获取当前矩形坐标
        x1, y1, x2, y2 = self.canvas.coords(self.rect_id)
        
        # 确保坐标正确
        x1, x2 = min(x1, x2), max(x1, x2)
        y1, y2 = min(y1, y2), max(y1, y2)
        
        # 获取屏幕截图
        screenshot = ImageGrab.grab(bbox=(x1, y1, x2, y2))
        
        # 添加边框
        border_size = self.settings["screenshot_border_size"]
        border_color = self.settings["screenshot_border_color"]
        if border_size > 0:
            bordered_image = Image.new('RGB', 
                (screenshot.width + border_size * 2, 
                 screenshot.height + border_size * 2), 
                border_color
            )
            bordered_image.paste(screenshot, (border_size, border_size))
            screenshot = bordered_image
        
        # 销毁截图界面
        self.root.unbind("<Escape>")
        self.root.unbind("<Return>")
        self.canvas.destroy()
        
        # 回调主程序
        self.callback(screenshot)


class ImagePreviewCard:
    def __init__(self, root, image, settings):
        self.root = root
        self.settings = settings
        self.preview_window = tk.Toplevel(root)
        self.preview_window.title("截图预览")
        self.preview_window.attributes("-topmost", True)
        self.preview_window.geometry("+100+100")
        
        # 设置窗口样式
        self.preview_window.config(bg="#333333")
        
        # 添加边框
        self.canvas = Canvas(self.preview_window, bg="#333333", highlightthickness=0)
        self.canvas.pack(fill="both", expand=True)
        
        # 转换图像用于显示
        self.image = image
        self.tk_image = ImageTk.PhotoImage(image)
        
        # 在画布上显示图像
        self.image_id = self.canvas.create_image(
            10, 10, anchor="nw", image=self.tk_image
        )
        
        # 添加控制按钮
        self.add_control_buttons()
        
        # 更新窗口大小
        self.update_window_size()
        
        # 绑定拖动事件
        self.canvas.bind("<ButtonPress-1>", self.start_drag)
        self.canvas.bind("<B1-Motion>", self.on_drag)
        self.canvas.bind("<ButtonRelease-1>", self.stop_drag)
        
        # 绑定退出事件
        self.preview_window.bind("<Escape>", self.close)
        
        # 初始位置
        self.start_x = 0
        self.start_y = 0
        self.dragging = False
    
    def update_window_size(self):
        """更新窗口大小以适应图像"""
        img_width = self.image.width
        img_height = self.image.height
        self.preview_window.geometry(f"{img_width + 20}x{img_height + 40}")
    
    def add_control_buttons(self):
        """添加控制按钮"""
        # 按钮容器
        button_frame = Frame(self.preview_window, bg="#333333")
        button_frame.pack(fill="x", padx=10, pady=5)
        
        # 关闭按钮
        close_btn = tk.Button(
            button_frame, text="✕", 
            bg="#FF5252", fg="white",
            font=("Arial", 10, "bold"),
            width=3, relief="flat",
            command=self.close
        )
        close_btn.pack(side="right")
    
    def start_drag(self, event):
        """开始拖动窗口"""
        self.start_x = event.x
        self.start_y = event.y
        self.dragging = True
    
    def on_drag(self, event):
        """拖动窗口"""
        if self.dragging:
            x = self.preview_window.winfo_x() + (event.x - self.start_x)
            y = self.preview_window.winfo_y() + (event.y - self.start_y)
            self.preview_window.geometry(f"+{x}+{y}")
    
    def stop_drag(self, event):
        """停止拖动"""
        self.dragging = False
    
    def close(self, event=None):
        """关闭预览窗口"""
        self.preview_window.destroy()


class OCRThread(threading.Thread):
    def __init__(self, image, settings, callback):
        super().__init__()
        self.image = image
        self.settings = settings
        self.callback = callback
        self.error = None
    def send_ocr_request(self, model, base_url, api_key, base64_image):
        """
        发送API请求以分析图片并生成Geogebra指令。

        :param base64_image: 经过Base64编码的图片数据
        :return: API响应中的结果文本
        """
        # 准备API请求
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        }

        # 创建请求体
        payload = {
            "model": model,
            "messages": [
                {
                    "role": "system",
                    "content": [
                        {
                            "type": "text",
                            "text": OCR_PROMPT
                        }
                    ]
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/png;base64,{base64_image}"
                            }
                        }
                    ]
                }
            ],
            "max_tokens": 8000
        }

        # 发送API请求
        response = requests.post(
            base_url, 
            headers=headers, 
            json=payload
        )
        response.raise_for_status()
        
        # 解析响应
        data = response.json()
        return data["choices"][0]["message"]["content"]

    def generate_html(self, model, base_url, api_key, result_text):
        """
        生成HTML演示课件的API请求并获取响应结果。

        :param result_text: 分析图片生成的Geogebra指令文本
        :return: API响应中的HTML内容
        """
        # 准备API请求
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        }

        # 创建请求体
        payload = {
            "model": model,
            "messages": [
                {
                    "role": "system",
                    "content": [
                        {
                            "type": "text",
                            "text": GEN_HTML_PROMPT
                        }
                    ]
                },
                {
                    "role": "user",
                    "content": [
                        {
                            "type": "text",
                            "text": result_text
                        }
                    ]
                }
            ]
        }
        
        # 发送API请求
        response = requests.post(
            base_url, 
            headers=headers, 
            json=payload
        )
        response.raise_for_status()
        
        # 解析响应
        data = response.json()
        return data["choices"][0]["message"]["content"]


    def run(self):
        """执行任务"""
        try:
            # 将图像转换为字节流
            buffered = io.BytesIO()
            self.image.save(buffered, format="PNG")
            img_data = buffered.getvalue()
            
            # 将图像转换为Base64
            base64_image = base64.b64encode(img_data).decode('utf-8')
            
            # 调用封装方法发送请求
            result_text = self.send_ocr_request(base64_image)
            
            # 调用封装方法生成 HTML
            result_text = self.generate_html(result_text)
            
            # 回调主线程
            self.callback(result_text)
            
        except Exception as e:
            self.error = str(e)
            self.callback(None)


class ScreenshotApp:
    def __init__(self, root):
        self.root = root
        self.root.title("截图识别工具")
        self.root.geometry("1000x700")  # 增大窗口尺寸
        self.root.resizable(True, True)
        
        # 加载设置
        self.settings = DEFAULT_SETTINGS.copy()
        
        # 样式配置
        self.style = ttk.Style()
        self.style.configure("TButton", font=("Arial", 10), padding=6)
        self.style.configure("Title.TLabel", font=("Arial", 16, "bold"))
        self.style.configure("Status.TLabel", font=("Arial", 9), foreground="#666666")
        
        # 应用图标
        try:
            self.root.iconbitmap("icon.ico")
        except:
            pass
        
        # 当前截图
        self.current_screenshot = None
        self.tk_image = None
        
        # 创建UI
        self.create_ui()
        
        # 状态变量
        self.ocr_in_progress = False
        self.progress_window = None  # 进度窗口

    def create_ui(self):
        """创建应用界面"""
        # 主布局
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill="both", expand=True, padx=20, pady=20)
        
        # 顶部工具栏
        toolbar_frame = ttk.Frame(main_frame)
        toolbar_frame.pack(fill="x", pady=(0, 20))
        
        # 标题
        title_label = ttk.Label(
            toolbar_frame, 
            text="截图识别工具", 
            style="Title.TLabel"
        )
        title_label.pack(side="left")
        
        # 按钮容器
        button_frame = ttk.Frame(toolbar_frame)
        button_frame.pack(side="right")
        
        # 截图按钮
        self.capture_btn = ttk.Button(
            button_frame, 
            text="截图", 
            command=self.start_capture,
            style="TButton"
        )
        self.capture_btn.pack(side="left", padx=5)
        
        # 识别按钮
        self.ocr_btn = ttk.Button(
            button_frame, 
            text="识别", 
            command=self.start_ocr,
            state="disabled",
            style="TButton"
        )
        self.ocr_btn.pack(side="left", padx=5)
        
        # 设置按钮
        self.settings_btn = ttk.Button(
            button_frame, 
            text="设置", 
            command=self.open_settings,
            style="TButton"
        )
        self.settings_btn.pack(side="left", padx=5)
        
        # 内容区域
        content_frame = ttk.Frame(main_frame)
        content_frame.pack(fill="both", expand=True)
        
        # 左侧截图预览（放大区域）
        preview_frame = ttk.LabelFrame(content_frame, text="截图预览")
        preview_frame.pack(side="left", fill="both", expand=True, padx=(0, 10))
        
        self.preview_label = ttk.Label(
            preview_frame, 
            text="截取的图片将显示在这里（点击查看大图）",
            anchor="center",
            background="#f0f0f0",
            cursor="hand2"  # 添加手型光标
        )
        self.preview_label.pack(fill="both", expand=True, padx=10, pady=10)
        
        # 绑定点击事件（查看大图）
        self.preview_label.bind("<Button-1>", self.show_large_preview)
        
        # 右侧识别结果
        result_frame = ttk.LabelFrame(content_frame, text="识别结果")
        result_frame.pack(side="right", fill="both", expand=True, padx=(10, 0))
        
        # 滚动文本框
        scrollbar = ttk.Scrollbar(result_frame)
        scrollbar.pack(side="right", fill="y")
        
        self.result_text = tk.Text(
            result_frame, 
            wrap="word", 
            yscrollcommand=scrollbar.set,
            font=("Arial", 11),
            padx=10, pady=10,
            relief="flat"
        )
        self.result_text.pack(fill="both", expand=True)
        
        scrollbar.config(command=self.result_text.yview)
        
        # 初始文本
        # self.result_text.insert("end", "识别结果将显示在这里...")
        # self.result_text.configure(state="disabled")
        
        # # 状态栏
        # status_frame = ttk.Frame(self.root)
        # status_frame.pack(fill="x", padx=20, pady=(0, 10))
        
        # self.status_label = ttk.Label(
        #     status_frame, 
        #     text="就绪", 
        #     style="Status.TLabel"
        # )
        # self.status_label.pack(side="left")
        
        # # 版权信息
        # copyright_label = ttk.Label(
        #     status_frame, 
        #     text="© 2023 截图识别工具", 
        #     style="Status.TLabel"
        # )
        # copyright_label.pack(side="right")
    
    def open_settings(self):
        """打开设置对话框"""
        SettingsDialog(self.root, self.settings)
    
    def start_capture(self):
        """开始截图"""
        # self.status_label.config(text="准备截图中...")
        self.root.update()
        
        # 隐藏主窗口
        self.root.withdraw()
        
        # 短暂的延迟确保窗口隐藏
        self.root.after(300, self.show_screenshot_tool)
    
    def show_screenshot_tool(self):
        """显示截图工具"""
        # 创建全屏窗口用于截图
        self.screenshot_window = tk.Toplevel(self.root)
        self.screenshot_window.attributes("-fullscreen", True)
        self.screenshot_window.attributes("-alpha", 0.3)
        self.screenshot_window.attributes("-topmost", True)
        self.screenshot_window.config(bg="black")
        
        # 创建截图工具
        self.screenshot_tool = ScreenshotTool(
            self.screenshot_window, 
            self.handle_screenshot_result,
            self.settings
        )
    
    def handle_screenshot_result(self, screenshot):
        """处理截图结果"""
        # 销毁截图窗口
        if self.screenshot_window:
            self.screenshot_window.destroy()
        
        # 显示主窗口
        self.root.deiconify()
        
        if screenshot:
            self.current_screenshot = screenshot
            # self.status_label.config(text=f"截图成功! 尺寸: {screenshot.width}x{screenshot.height}")
            
            # 显示预览
            self.show_preview(screenshot)
            
            # 启用识别按钮
            self.ocr_btn.config(state="normal")
        # else:
        #     self.status_label.config(text="截图已取消")
    
    def show_preview(self, screenshot):
        """在主界面显示截图预览"""
        # 调整图像大小以适应预览区域
        preview_width = self.preview_label.winfo_width() - 20
        preview_height = self.preview_label.winfo_height() - 20
        
        if preview_width < 10:
            preview_width = 400  # 放大预览区域
        if preview_height < 10:
            preview_height = 300  # 放大预览区域
        
        # 调整图像大小
        img_width, img_height = screenshot.size
        ratio = min(preview_width / img_width, preview_height / img_height)
        new_width = int(img_width * ratio)
        new_height = int(img_height * ratio)
        
        resized_img = screenshot.resize((new_width, new_height), Image.LANCZOS)
        
        # 转换为Tkinter图像
        self.tk_image = ImageTk.PhotoImage(resized_img)
        self.preview_label.config(image=self.tk_image, text="")
    
    def show_large_preview(self, event=None):
        """显示大图预览"""
        if self.current_screenshot:
            self.preview_card = ImagePreviewCard(self.root, self.current_screenshot, self.settings)
    
    def create_progress_window(self):
        """创建进度窗口"""
        self.progress_window = tk.Toplevel(self.root)
        self.progress_window.title("识别中...")
        self.progress_window.geometry("300x100")
        self.progress_window.attributes("-topmost", True)
        self.progress_window.resizable(False, False)
        
        # 添加半透明蒙版
        self.progress_window.attributes("-alpha", 0.7)
        
        # 进度条
        progress_label = ttk.Label(
            self.progress_window,
            text="正在识别图像内容，请稍候...",
            font=("Arial", 10)
        )
        progress_label.pack(pady=(10, 5))
        
        self.progress_bar = ttk.Progressbar(
            self.progress_window,
            orient="horizontal",
            length=280,
            mode="indeterminate"
        )
        self.progress_bar.pack(pady=5)
        
        # 开始进度条动画
        self.progress_bar.start(10)
    
    def close_progress_window(self):
        """关闭进度窗口"""
        if self.progress_window:
            self.progress_bar.stop()
            self.progress_window.destroy()
            self.progress_window = None
    
    def start_ocr(self):
        """开始OCR识别"""
        if self.current_screenshot is None:
            messagebox.showwarning("警告", "请先截图")
            return
        
        if self.ocr_in_progress:
            messagebox.showinfo("提示", "识别正在进行中，请稍候...")
            return
        
        # 检查API设置
        if not self.settings["api_key"] or not self.settings["base_url"]:
            messagebox.showwarning("警告", "请先在设置中配置API密钥和基础URL")
            return
        
        # 更新状态
        self.ocr_in_progress = True
        # self.status_label.config(text="正在识别图像内容...")
        self.result_text.configure(state="normal")
        self.result_text.delete("1.0", "end")
        self.result_text.insert("end", "识别中，请稍候...")
        self.result_text.configure(state="disabled")
        self.ocr_btn.config(state="disabled")
        self.root.update()
        
        # 创建进度窗口
        self.create_progress_window()
        
        # 在新线程中执行OCR
        self.ocr_thread = OCRThread(
            self.current_screenshot,
            self.settings,
            self.handle_ocr_result
        )
        self.ocr_thread.start()
        
        # 检查线程状态的定时器
        self.check_ocr_thread()
    
    def check_ocr_thread(self):
        """检查OCR线程状态"""
        if self.ocr_thread.is_alive():
            # 线程仍在运行，稍后再次检查
            self.root.after(100, self.check_ocr_thread)
        else:
            # 线程已完成
            self.ocr_in_progress = False
            self.ocr_btn.config(state="normal")
            self.close_progress_window()
    
    def handle_ocr_result(self, result):
        """处理OCR识别结果"""
        if result:
            # self.status_label.config(text="识别完成!")
            self.result_text.configure(state="normal")
            self.result_text.delete("1.0", "end")
            self.result_text.insert("end", result)
            self.result_text.configure(state="disabled")
        else:
            error_msg = self.ocr_thread.error or "识别过程中发生错误"
            # self.status_label.config(text=error_msg)
            messagebox.showerror("识别错误", error_msg)


if __name__ == "__main__":
    root = tk.Tk()
    app = ScreenshotApp(root)
    
    # 设置应用样式
    root.tk_setPalette(background="#f5f5f5")
    root.style = ttk.Style()
    root.style.configure(".", font=("Arial", 10))
    root.style.configure("TButton", padding=6)
    root.style.configure("TFrame", background="#ffffff")
    root.style.configure("TLabel", background="#ffffff")
    root.style.configure("TLabelframe", background="#ffffff")
    root.style.configure("TLabelframe.Label", background="#ffffff")
    
    # 运行应用
    root.mainloop()